//
// Created by 文道江 on 16/1/8.
// Copyright (c) 2016 文道江. All rights reserved.
//

#import "WebViewClient.h"
#import "HybridBridge.h"


@implementation WebViewClient {
}

- (instancetype)initWithController:(UIViewController *)controller {
    self = [super init];
    if (self) {
        _controller = controller;
    }

    return self;
}

+ (instancetype)clientWithController:(UIViewController *)controller {
    return [[self alloc] initWithController:controller];
}


- (WKWebViewJavascriptBridge *)bridgeForWebView:(WVJB_WEBVIEW_TYPE*)webView handler:(WVJBHandler)handler {
    return [WKWebViewJavascriptBridge bridgeForWebView:webView webViewDelegate:self handler:handler];
}

- (WKWebViewJavascriptBridge *)bridgeForWebView:(WVJB_WEBVIEW_TYPE*)webView webViewDelegate:(WVJB_WEBVIEW_DELEGATE_TYPE*)webViewDelegate handler:(WVJBHandler)messageHandler {
    _webDelegate = webViewDelegate;
    return [WKWebViewJavascriptBridge bridgeForWebView:webView webViewDelegate:self handler:messageHandler resourceBundle:nil];
}

- (WKWebViewJavascriptBridge *)bridgeForWebView:(WVJB_WEBVIEW_TYPE*)webView webViewDelegate:(WVJB_WEBVIEW_DELEGATE_TYPE*)webViewDelegate handler:(WVJBHandler)messageHandler resourceBundle:(NSBundle*)bundle {
    _webDelegate = webViewDelegate;
    return [WKWebViewJavascriptBridge bridgeForWebView:webView webViewDelegate:self handler:messageHandler resourceBundle:bundle];
}


- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients {
    SendSMSController *controller = [[SendSMSController alloc] initWithBody:bodyOfMessage address:recipients];
    if([SendSMSController canSendText]) {
        controller.body = bodyOfMessage;
        controller.recipients = recipients;
        [_controller presentViewController:controller animated:YES completion:nil];
    }
}

#pragma mark webView delegate

/*- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    [[HybridEventBus defaultEventBus] postData:@{
            @"webView": webView,
            @"request": request,
            @"navigationType": @(navigationType)
    } Tag:@"shouldStartLoadWithRequest"];

    __strong typeof(_webDelegate) strongDelegate = _webDelegate;
    if ([request.URL.scheme isEqualToString:@"sms"]){
        NSString *body = [request.URL.query stringByReplacingOccurrencesOfString:@"body=" withString:@""];
        [self sendSMS:body.urlDecodedString recipientList:@[request.URL.host]];
        return NO;
    } else if (strongDelegate && [strongDelegate respondsToSelector:@selector(webView:shouldStartLoadWithRequest:navigationType:)]) {
        return [strongDelegate webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
    } else {
        return YES;
    }
}

- (void)webViewDidStartLoad:(UIWebView *)webView {

    [[HybridEventBus defaultEventBus] postData:@{
            @"webView": webView
    } Tag:@"webViewDidStartLoad"];

    __strong typeof(_webDelegate) strongDelegate = _webDelegate;
    if (strongDelegate && [strongDelegate respondsToSelector:@selector(webViewDidStartLoad:)]) {
        [strongDelegate webViewDidStartLoad:webView];
    }
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {

    [[HybridEventBus defaultEventBus] postData:@{
            @"webView": webView
    } Tag:@"webViewDidFinishLoad"];

    __strong typeof(_webDelegate) strongDelegate = _webDelegate;
    if (strongDelegate && [strongDelegate respondsToSelector:@selector(webViewDidFinishLoad:)]) {
        [strongDelegate webViewDidFinishLoad:webView];
    }
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {

    [[HybridEventBus defaultEventBus] postData:@{
            @"webView": webView,
            @"error": error
    } Tag:@"didFailLoadWithError"];

    __strong typeof(_webDelegate) strongDelegate = _webDelegate;
    if (strongDelegate && [strongDelegate respondsToSelector:@selector(webView:didFailLoadWithError:)]) {
        [strongDelegate webView:webView didFailLoadWithError:error];
    }
}*/

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {

    NSURLRequest *request = navigationAction.request;

    [[HybridEventBus defaultEventBus] postData:@{
            @"webView": webView,
            @"request": request,
            @"navigationType": @(navigationAction.navigationType)
    } Tag:@"shouldStartLoadWithRequest"];

    __strong typeof(_webDelegate) strongDelegate = _webDelegate;
    if ([request.URL.scheme isEqualToString:@"sms"]){
        NSString *body = [request.URL.query stringByReplacingOccurrencesOfString:@"body=" withString:@""];
        [self sendSMS:body.urlDecodedString recipientList:@[request.URL.host]];
        decisionHandler(WKNavigationActionPolicyCancel);
        return ;
    }else if ([request.URL.scheme isEqualToString:@"tel"]){
        UIApplication *app = [UIApplication sharedApplication];
        if ([app canOpenURL:request.URL]) {
            [app openURL:request.URL];
            // 一定要加上这句,否则会打开新页面
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }else if([request.URL.absoluteString rangeOfString:@"itunes.apple.com"].location != NSNotFound){
        UIApplication *app = [UIApplication sharedApplication];
        if([app canOpenURL:request.URL]){
            [app openURL:request.URL];
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    } else if (strongDelegate && [strongDelegate respondsToSelector:@selector(webView:decidePolicyForNavigationAction:decisionHandler:)]) {
        //[strongDelegate webView:webView shouldStartLoadWithRequest:request navigationType:navigationAction.navigationType];
        [strongDelegate webView:webView decidePolicyForNavigationAction:navigationAction decisionHandler:decisionHandler];
        return;
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
    [[HybridEventBus defaultEventBus] postData:@{
            @"webView": webView
    } Tag:@"webViewDidStartLoad"];

    __strong typeof(_webDelegate) strongDelegate = _webDelegate;
    if (strongDelegate && [strongDelegate respondsToSelector:@selector(webView:didStartProvisionalNavigation:)]) {
        [strongDelegate webView:webView didFinishNavigation:navigation];
    }
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    [[HybridEventBus defaultEventBus] postData:@{
            @"webView": webView
    } Tag:@"webViewDidFinishLoad"];

    __strong typeof(_webDelegate) strongDelegate = _webDelegate;
    if (strongDelegate && [strongDelegate respondsToSelector:@selector(webView:didFinishNavigation:)]) {
        [strongDelegate webView:webView didFinishNavigation:navigation];
    }
}

- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    [[HybridEventBus defaultEventBus] postData:@{
            @"webView": webView,
            @"error": error
    } Tag:@"didFailLoadWithError"];
    __strong typeof(_webDelegate) strongDelegate = _webDelegate;
    if(strongDelegate && [strongDelegate respondsToSelector:@selector(webView:didFailLoadWithError:)]){
        [strongDelegate webView:webView didFailNavigation:navigation withError:error];
    }
}

@end